<?php

class MenuController extends BackendController
{
	public $parentUrl;
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','create_sub','view_detail','delete','delete_sub'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	
	public function actionView_detail($id)
	{
		try{
			$model = new SubMenu();
			$data = $model->getAll($id);
			$this->render('view_detail',array(
				'data' => $data,
				'parentUrl' => $this->parentUrl,
				'id' => $id
			));
		}catch(Exception $e){
			Yii::log("Invalid request. Please do not repeat this request again.");
            echo "<pre>";
            var_dump($e);
            echo "</pre>";
            die();
		}
	}

	public function actionCreate()
	{
		$model=new Menu;
		$content = new Content();
		if(isset($_POST['Menu']))
		{
			$content['Short_Descriptions'] = $_POST['Content']['Short_Descriptions'];
            $content['Descriptions'] = $_POST['Content']['Descriptions'];
            $content['CreateDate'] = date('Y-m-d H:i:s');
 			$content->save();
 			$content_id = $content['ContentId'];
			$model->attributes=$_POST['Menu'];
			$model['ContentId'] = $content_id;
			$model->MenuNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->MenuName)));
			//$icon = CUploadedFile::getInstance($model, 'Icon');
			$model->validate();
			// if ($icon) {
   //              $icon->saveAs(Yii::app()->theme->baseUrl . "/frontend/images/$model->Icon");
   //              //$model->Icon = MyFunctionCustom::saveSlide($model, $icon);
   //              $model->Icon = $icon->name;
   //          }
			if($model->save())
				$this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/menu/index'));
		}

		$this->render('create',array(
			'model'=>$model,
			'content' =>$content,
		));
	}

	public function actionCreate_sub($id){
		$model=new SubMenu();
		$content = new Content();
		if(isset($_POST['SubMenu']))
		{
			$content['Short_Descriptions'] = $_POST['Content']['Short_Descriptions'];
            $content['Descriptions'] = $_POST['Content']['Descriptions'];
            $content['CreateDate'] = date('Y-m-d H:i:s');
 			$content->save();
 			$content_id = $content['ContentId'];
			$model->attributes=$_POST['SubMenu'];
			$model->MenuId = $id;
			$model['ContentId'] = $content_id;
			$model->SubMenuNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->SubMenuName)));
			//$icon = CUploadedFile::getInstance($model, 'Icon');
			$model->validate();
			// if ($icon) {
   //              $icon->saveAs(Yii::app()->theme->baseUrl . "/frontend/images/$model->Icon");
   //              //$model->Icon = MyFunctionCustom::saveSlide($model, $icon);
   //              $model->Icon = $icon->name;
   //          }
			if($model->save())
				$this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/menu/view_detail/id/'.$id));
		}
		$menu = Menu::model()->findByPk($id);
		$this->render('create_sub',array(
			'model'=>$model,
			'content' =>$content,
			'menu' => $menu,
			'id' => $id,
		));
	}
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$content = Content::model()->findByPk($model->ContentId);
		
		if(isset($_POST['Menu']))
		{
			$content->attributes = $_POST['Content'];
            $content['UpdateDate'] = date('Y-m-d H:i:s');
            $content->save();
			$model->attributes=$_POST['Menu'];
			$model->MenuNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->MenuName)));
			if($model->save())
				$this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/menu/index'));
		}

		$this->render('update',array(
			'model'=>$model,
			'content' =>$content,
		));
	}

	public function actionUpdate_sub($id)
	{
		$model=$this->loadModel($id);
		$content = Content::model()->findByPk($model->ContentId);
		
		if(isset($_POST['SubMenu']))
		{
			$content->attributes = $_POST['Content'];
            $content['UpdateDate'] = date('Y-m-d H:i:s');
            $content->save();
			$model->attributes=$_POST['SubMenu'];
			$model->SubMenuNameRewrite = str_replace(" ", "-", strtolower(StringHelper::remove_vietnamese_accents($model->SubMenuName)));
			if($model->save())
				$this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . '/store/backend/menu/index'));
		}

		$this->render('update_sub',array(
			'model'=>$model,
			'content' =>$content,
		));
	}
	public function actionDelete()
	{
		$model = Menu::model()->findByPk($_POST['id']);
		if(isset($model)){
			$content1 = Content::model()->findByPk($model->ContentId);
			$MenuId = $model->MenuId;		
			$sub = SubMenu::model()->findAllByAttributes(array('MenuId' => $model->MenuId));
			if(isset($sub)){				
				$arrContentId = array();
				
				SubMenu::model()->deleteAll('`MenuId`="'.$MenuId.'"');
	            foreach ($sub as $key => $value) {
					Content::model()->deleteAll('`ContentId`="'.$value['ContentId'] .'"');
				}
			}

			if($this->loadModel($_POST['id'])->delete()){
				if(isset($content1))
					$content1->delete();
				echo CJSON::encode(1);
			}
		}
	}

	public function actionDelete_sub()
	{
		$model = SubMenu::model()->findByPk($_POST['id']);
		if(isset($model)){
			$content = Content::model()->findByPk($model->ContentId);			
			if($model->delete()){
				if(isset($content))
					$content->delete();
				echo CJSON::encode(1);
			}
		}
	}

	public function actionIndex(){
		try{
			$model = new Menu();
			$data = $model->getAll();
			$this->render('index',array(
				'data' => $data,
				'parentUrl' => $this->parentUrl
			));
		}catch(Exception $e){
			Yii::log("Invalid request. Please do not repeat this request again.");
            echo "<pre>";
            var_dump($e);
            echo "</pre>";
            die();
		}
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Menu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Menu']))
			$model->attributes=$_GET['Menu'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Menu the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Menu::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Menu $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='menu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
